package com.midian.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.midian.common.system.SysStatic;
import com.midian.model.user.vo.UserInfoVo;

/**
 * 
 * @Title:过滤器  
 * @Desription:登录过滤器
 * @Company:MDKG
 * @ClassName:LoginFilter.java
 * @Author:zhucong
 * @CreateDate:2013-6-7 下午5:54:21  
 * @UpdateUser:zhucong
 * @Version:0.1
 */
public class LoginFilter implements Filter {
	
    public LoginFilter() {
    	
    }

	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpResponse = (HttpServletResponse)response;
		String contextPath = httpRequest.getContextPath();
		//判断请求路径
		String requestURI = httpRequest.getRequestURI();
		
		//后台的URL才进行拦截
		if(requestURI.indexOf("/mc/") != -1) {
			//当打开的是登录页面，或者执行登录Action时，直接执行
			if (requestURI.equals(contextPath + "/mc/login.jsp") || requestURI.equals(contextPath + "/mc/userlogin")) {
				chain.doFilter(request, response);
				return;
			}
			//判断用户是否已经登录
			UserInfoVo userInfo = (UserInfoVo) httpRequest.getSession().getAttribute(SysStatic.MC_LOGIN);
			if (userInfo == null) {
				//当session为空时跳登录页面
				httpResponse.sendRedirect(contextPath+"/mc/login.jsp");
				return;
				//当session不为空而且地址为/mc/时跳主页
			} else if(requestURI.equals(contextPath + "/mc/")) {
				httpResponse.sendRedirect(contextPath+"/mc/index.jsp");
				return;
			}
		}
		chain.doFilter(request, response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		/*ServletContext sc = fConfig.getServletContext();
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sc);*/
	}
}
